<template>
  <div class="goods-edit">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="page-title">{{ isEdit ? '编辑商品' : '新增商品' }}</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">
          <i class="el-icon-back"></i> 返回列表
        </el-button>
      </div>
      
      <el-form :model="goodsForm" :rules="rules" ref="goodsForm" label-width="120px" class="goods-form">
        <!-- 基本信息 -->
        <el-card class="form-section" shadow="never">
          <div slot="header" class="section-header">
            <span class="section-title">基本信息</span>
          </div>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input 
                  id="goods_name"
                  v-model.trim="goodsForm.goods_name" 
                  placeholder="请输入商品名称">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品编号" prop="goods_no">
                <el-input 
                  id="goods_no"
                  v-model.trim="goodsForm.goods_no" 
                  placeholder="请输入商品编号">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品简称" prop="short_name">
                <el-input 
                  id="short_name"
                  v-model.trim="goodsForm.short_name" 
                  placeholder="请输入商品简称">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品别名" prop="alias">
                <el-input 
                  id="alias"
                  v-model.trim="goodsForm.alias" 
                  placeholder="请输入商品别名">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="品牌" prop="brand_id">
                <el-select 
                  id="brand_id"
                  v-model="goodsForm.brand_id" 
                  placeholder="请选择品牌" 
                  style="width: 100%">
                  <el-option
                    v-for="item in brandOptions"
                    :key="item.brand_id"
                    :label="item.brand_name"
                    :value="item.brand_id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品分类" prop="class_id">
                <el-select 
                  id="class_id"
                  v-model="goodsForm.class_id" 
                  placeholder="请选择商品分类" 
                  style="width: 100%">
                  <el-option
                    v-for="item in classOptions"
                    :key="item.class_id"
                    :label="item.class_name"
                    :value="item.class_id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品类型" prop="goods_type">
                <el-select 
                  id="goods_type"
                  v-model="goodsForm.goods_type" 
                  placeholder="请选择商品类型" 
                  style="width: 100%">
                  <el-option label="普通商品" :value="1"></el-option>
                  <el-option label="特殊商品" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产地" prop="origin">
                <el-input 
                  id="origin"
                  v-model.trim="goodsForm.origin" 
                  placeholder="请输入产地">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input 
                  id="remark"
                  type="textarea" 
                  v-model.trim="goodsForm.remark" 
                  placeholder="请输入备注信息"
                  :rows="3">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="属性1" prop="prop1">
                <el-input 
                  id="prop1"
                  v-model.trim="goodsForm.prop1" 
                  placeholder="请输入属性1">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="属性2" prop="prop2">
                <el-input 
                  id="prop2"
                  v-model.trim="goodsForm.prop2" 
                  placeholder="请输入属性2">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="属性3" prop="prop3">
                <el-input 
                  id="prop3"
                  v-model.trim="goodsForm.prop3" 
                  placeholder="请输入属性3">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="属性4" prop="prop4">
                <el-input 
                  id="prop4"
                  v-model.trim="goodsForm.prop4" 
                  placeholder="请输入属性4">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="属性5" prop="prop5">
                <el-input 
                  id="prop5"
                  v-model.trim="goodsForm.prop5" 
                  placeholder="请输入属性5">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="属性6" prop="prop6">
                <el-input 
                  id="prop6"
                  v-model.trim="goodsForm.prop6" 
                  placeholder="请输入属性6">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 商品规格 -->
        <el-card class="form-section" shadow="never">
          <div slot="header" class="section-header">
            <span class="section-title">商品规格</span>
            <el-button type="primary" size="small" @click="addSpec">
              <i class="el-icon-plus"></i> 添加规格
            </el-button>
          </div>
          
          <div class="specs-container">
            <el-table 
              :data="goodsForm.specs" 
              border 
              style="width: 100%"
              :header-cell-style="{ background: '#f5f7fa' }"
              v-loading="specsLoading">
              <el-table-column prop="spec_name" label="规格名称" min-width="180">
                <template slot-scope="scope">
                  <el-input v-model.trim="scope.row.spec_name" placeholder="请输入规格名称"></el-input>
                </template>
              </el-table-column>
              
              <el-table-column prop="spec_code" label="规格编码" min-width="180">
                <template slot-scope="scope">
                  <el-input v-model.trim="scope.row.spec_code" placeholder="请输入规格编码"></el-input>
                </template>
              </el-table-column>
              
              <el-table-column prop="retail_price" label="零售价" width="150">
                <template slot-scope="scope">
                  <el-input-number 
                    v-model="scope.row.retail_price" 
                    :precision="2" 
                    :step="0.1" 
                    :min="0"
                    controls-position="right"
                    style="width: 100%">
                  </el-input-number>
                </template>
              </el-table-column>
              
              <el-table-column prop="wholesale_price" label="批发价" width="150">
                <template slot-scope="scope">
                  <el-input-number 
                    v-model="scope.row.wholesale_price" 
                    :precision="2" 
                    :step="0.1" 
                    :min="0"
                    controls-position="right"
                    style="width: 100%">
                  </el-input-number>
                </template>
              </el-table-column>
              
              <el-table-column prop="market_price" label="市场价" width="150">
                <template slot-scope="scope">
                  <el-input-number 
                    v-model="scope.row.market_price" 
                    :precision="2" 
                    :step="0.1" 
                    :min="0"
                    controls-position="right"
                    style="width: 100%">
                  </el-input-number>
                </template>
              </el-table-column>
              
              <el-table-column label="操作" width="100" fixed="right">
                <template slot-scope="scope">
                  <el-button 
                    type="danger" 
                    size="mini" 
                    icon="el-icon-delete"
                    circle
                    @click="removeSpec(scope.$index)">
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div v-if="goodsForm.specs.length === 0" class="empty-specs">
              <el-empty description="暂无规格数据"></el-empty>
            </div>
          </div>
        </el-card>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="submitForm" :loading="submitting">
            <i class="el-icon-check"></i> 保存
          </el-button>
          <el-button @click="goBack">
            <i class="el-icon-close"></i> 取消
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getGoodsDetail, createOrUpdateGoods, deleteGoodsSpec } from '@/api/goods'
import { getBrandList } from '@/api/brand'
import { getClassList } from '@/api/class'

export default {
  name: 'GoodsEdit',
  data() {
    return {
      isEdit: false,
      submitting: false,
      specsLoading: false,
      goodsForm: this.getInitialFormData(),
      brandOptions: [],
      classOptions: [],
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        goods_no: [
          { required: true, message: '请输入商品编号', trigger: 'blur' }
        ],
        brand_id: [
          { required: true, message: '请选择品牌', trigger: 'change' }
        ],
        class_id: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    '$route.params.id': {
      handler(newVal) {
        if (newVal) {
          this.isEdit = true
          this.getGoodsDetail(newVal)
        } else {
          this.isEdit = false
          this.resetForm()
        }
      },
      immediate: true
    }
  },
  created() {
    this.initData()
  },
  beforeDestroy() {
    // 清理所有可能的监听器
    this.$off()
    // 清理定时器
    if (this.timer) {
      clearTimeout(this.timer)
    }
  },
  mounted() {
    // 确保在组件挂载后数据已经准备好
    this.$nextTick(() => {
      if (this.isEdit && this.$route.params.id) {
        this.getGoodsDetail(this.$route.params.id)
      }
    })
  },
  methods: {
    // 获取表单初始数据
    getInitialFormData() {
      return {
        goods_name: '',
        goods_no: '',
        short_name: '',
        alias: '',
        goods_type: 1,
        brand_id: '',
        brand_no: '',
        class_id: '',
        unit: '0',
        aux_unit: '0',
        flag_id: '0',
        properties: '0,0,0,0,0,0',
        version_id: '0',
        remark: '',
        prop1: '',
        prop2: '',
        prop3: '',
        prop4: '',
        prop5: '',
        prop6: '',
        origin: '',
        specs: []
      }
    },

    // 重置表单
    resetForm() {
      const initialData = this.getInitialFormData()
      this.$set(this, 'goodsForm', initialData)
      if (this.$refs.goodsForm) {
        this.$refs.goodsForm.resetFields()
      }
    },

    // 初始化数据
    async initData() {
      try {
        this.specsLoading = true
        // 并行获取品牌和分类数据
        await Promise.all([
          this.fetchBrandList(),
          this.fetchClassList()
        ])

        // 如果是编辑模式，获取商品详情
        const goodsId = this.$route.params.id
        if (goodsId) {
          this.isEdit = true
          await this.getGoodsDetail(goodsId)
        } else {
          this.isEdit = false
          this.resetForm()
        }
      } catch (error) {
        this.$message.error('初始化数据失败: ' + (error.message || '未知错误'))
      } finally {
        this.specsLoading = false
      }
    },

    // 获取品牌列表
    async fetchBrandList() {
      try {
        const res = await getBrandList()
        if (res.data && res.data.items) {
          this.brandOptions = res.data.items
          return res.data.items
        }
        return []
      } catch (error) {
        this.$message.error('获取品牌列表失败')
        return []
      }
    },

    // 获取分类列表
    async fetchClassList() {
      try {
        const res = await getClassList()
        if (res.data && res.data.data && res.data.data.list) {
          this.classOptions = res.data.data.list
          return res.data.data.list
        }
        return []
      } catch (error) {
        this.$message.error('获取分类列表失败')
        return []
      }
    },

    // 获取商品详情
    async getGoodsDetail(id) {
      try {
        this.specsLoading = true
        const res = await getGoodsDetail(id)
        
        // 检查响应数据结构
        if (res) {
          // 尝试获取正确的数据路径
          const goodsData = res.data?.data || res.data || res
          if (!goodsData || Object.keys(goodsData).length === 0) {
            this.$message.error('获取商品详情失败：数据为空')
            return
          }

          // 确保在设置数据之前，品牌和分类数据已经准备好
          await this.ensureOptionsLoaded()
          this.goodsForm = goodsData.goods
          console.log(this.goodsForm)

        } else {
          this.$message.error('获取商品详情失败：响应为空')
        }
      } catch (error) {
        this.$message.error('获取商品详情失败：' + (error.message || '未知错误'))
      } finally {
        this.specsLoading = false
      }
    },

    // 确保选项数据已加载
    async ensureOptionsLoaded() {
      if (this.brandOptions.length === 0) {
        await this.fetchBrandList()
      }
      if (this.classOptions.length === 0) {
        await this.fetchClassList()
      }
    },

    // 设置表单数据
    setFormData(data) {
      if (!data) {
        return
      }
      // 创建一个新的表单数据对象
      const newFormData = { ...this.getInitialFormData() }
      
      // 遍历数据并设置到新对象中
      Object.keys(data).forEach(key => {
        if (key in newFormData) {
          const value = data[key]
          newFormData[key] = value
        } 
      })
      // 使用 Vue.set 更新整个表单对象
      this.$set(this, 'goodsForm', newFormData.goods)
      // 打印设置后的表单数据
      // 确保表单数据更新后重新验证
      this.$nextTick(() => {
        if (this.$refs.goodsForm) {
          this.$refs.goodsForm.clearValidate()
        }
      })
    },

    // 添加规格
    addSpec() {
      this.goodsForm.specs.push({
        goods_id: this.goodsForm.goods_id,
        spec_name: '',
        spec_code: '',
        retail_price: 0,
        wholesale_price: 0,
        market_price: 0
      })
    },

    // 删除规格
    removeSpec(index) {
      this.$confirm('确认删除该规格?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.goodsForm.specs.splice(index, 1)
        await deleteGoodsSpec(this.goodsForm.specs[index].spec_id)
        this.$message.success('删除成功')
      }).catch(() => {})
    },

    // 提交表单
    async submitForm() {
      try {
        await this.$refs.goodsForm.validate()
        this.submitting = true
        
        const submitData = {
          ...this.goodsForm,
          // 确保提交的数据格式正确
          goods_type: Number(this.goodsForm.goods_type),
          unit: String(this.goodsForm.unit),
          aux_unit: String(this.goodsForm.aux_unit),
          flag_id: String(this.goodsForm.flag_id),
          version_id: String(this.goodsForm.version_id)
        }

        if (this.isEdit) {
          await createOrUpdateGoods(submitData)
          this.$message.success('更新商品成功')
        } else {
          await createOrUpdateGoods(submitData)
          this.$message.success('创建商品成功')
        }
        
        this.goBack()
      } catch (error) {
        this.$message.error(error.message || '提交失败')
      } finally {
        this.submitting = false
      }
    },

    // 返回列表页
    goBack() {
      this.$router.push('/products/list')
    }
  }
}
</script>

<style lang="scss" scoped>
.goods-edit {
  .page-title {
    font-size: 18px;
    font-weight: bold;
  }

  .goods-form {
    .form-section {
      margin-bottom: 20px;

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .section-title {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
      }
    }

    .specs-container {
      margin-top: 10px;

      .empty-specs {
        padding: 40px 0;
      }
    }
  }

  .form-actions {
    margin-top: 30px;
    text-align: center;
  }

  .el-cascader {
    width: 100%;
  }

  // 表格样式优化
  .el-table {
    th {
      background-color: #f5f7fa !important;
    }

    .el-input-number {
      width: 100%;
    }
  }
}
</style> 